import AMapLoader from '@amap/amap-jsapi-loader';

const key = process.env.VUE_APP_webKey;
export async function getLocationName(lnglat) {

  const url = `https://restapi.amap.com/v3/geocode/regeo?location=${lnglat.lng},${lnglat.lat}&key=${key}`;
  try {
    const response = await fetch(url);
    const data = await response.json();
    if (data.status === '1' && data.regeocode) {
      return data.regeocode.formatted_address;
    } else {
      throw new Error('未找到地点名称');
    }
  } catch (error) {
    console.error('获取地点名称失败:', error);
    return null;
  }
}

export async function getLocationCoordinates(location) {
  const url = `https://restapi.amap.com/v3/geocode/geo?address=${encodeURIComponent(location)}&key=${key}`;
  const response = await fetch(url);
  const data = await response.json();
  if (data.status === '1' && data.geocodes.length > 0) {
    const locationData = data.geocodes[0];
    return locationData.location.split(',').map(Number);
  } else {
    throw new Error(`无法获取 ${location} 的坐标`);
  }
}

export async function initMap(plugins) {
  try {
    window._AMapSecurityConfig = {
      securityJsCode: "62a9a72d8d4d6f8ab7c5f9dbe864f044",
    };
    return  await AMapLoader.load({
      key: process.env.VUE_APP_webapiKey,
      version: "2.0",
      plugins: ["AMap.Scale", 'AMap.Geocoder', ...plugins],
    });
  } catch (err) {
    console.error(err);
  }
}

export async function getMapInstance(plugins = []) {
  return await initMap(plugins);
}

export const defaultMapOptions = {
  // center: [116.149672, 24.531716], // 新铺镇
  center: [116.122046, 24.288832], // 梅州市
  zoom: 15, //地图缩放级别
};

export async function createMap(el, options = defaultMapOptions, plugins = []) {
  try {
    const AMap  = await getMapInstance(plugins);
    return new AMap.Map(el, options);
  } catch (err) {
    console.error(err);
  }
}
